<script lang="ts" setup>
  import { reactive, ref  } from 'vue';
  import { Search, Edit, Delete } from '@element-plus/icons-vue';
  import check from '@/components/svgIcon/check.vue';
  import { ElMessageBox } from 'element-plus'

  const props = defineProps({
    table: {
      type: Array,
      default: () => []
    },
    total: {
      type: Number,
      default: 0
    },
    currentPage:{
      type:Number,// 当前页码
      default:1
    },
    pageSize:{
      type:Number,
      default: 10
    }
  });
  const emits = defineEmits (['onPageChange','onQueryChange','onOpenAdd','onDelete','onEdit'])
  // 是否可以删除
  let cannotDelete = ref(true);
  // 存放table选中的数据
  const tableSelections = ref<string[]>([])
  // 是否显示popover
  let visible = ref(false);
  // 排序按钮
  let datasourceFields = reactive([
    {
      name: '名称',
      value: 'name'
    },
    {
      name: '类型',
      value: 'type'
    },
    {
      name: '更新时间',
      value: 'createTime'
    }
  ]);
  let sortOptions = reactive([
    {
      name: '升序',
      value: 'asc'
    },
    {
      name: '降序',
      value: 'desc'
    }
  ]);
  // 用于查询的参数
  let queryParameters = reactive({
    datasourceName: '',
    selectField: 'createTime', // 排序字段
    sortMethod: 'desc' // 排序方式
  });

  // 排序选择
  const selectBack = (val: string, field: string) => {
    if (field === 'fields') {
      queryParameters.selectField = val;
    } else {
      queryParameters.sortMethod = val;
    }
    datasourceEnter()
  };
  // 查询
  const datasourceEnter = () => {
    emits('onQueryChange',queryParameters)
  };

  // 连接参数转换
  const connectParamConver = (row:any) => {
    try {
      if (['shapeFolder', 'fgdb', 'mdb'].indexOf(row.type) > -1) {
        if (row.fileSource === 'SMBstore') {
          return JSON.parse(row.config).path;
        } else {
          return row.config;
        }
      } else {
        const config = JSON.parse(row.config);
        return `${config.ip}:${config.port}/${config.database}`;
      }
    } catch (e) {
      console.error(e);
    }
  };

  // 页码切换
  const pageChange = (pageNum:number) => {
    emits('onPageChange',pageNum)
  }

  // 打开新增弹窗
  const openAdd = () =>{
    emits('onOpenAdd')
  }

  /*
  * @function deleteSource 删除数据源方法
  * @param row table当前行数据
  * */
  const deleteSource = (row:any) => {
    ElMessageBox.alert(
      `确定删除数据源<span style='color:#f00'>${row.name}</span>?`,
      '删除数据源',
      {
        dangerouslyUseHTMLString:true,
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        draggable:true
      }
    ).then(()=>{
      emits('onDelete','single',row)
    })
  }

  /*
  * @function editSource 编辑数据源方法
  *
  * */
  const editSource = (row:any) => {
    emits('onEdit',row)
  }

  // table列表多选
  const selectionChange = (selection:any) => {
    tableSelections.value = selection
  }
  // 批量删除数据源
  const batchDeleteSource = () =>{
    const ids = tableSelections.value.map(i=>i.idString)
    const names = tableSelections.value.map(i=>i.name)
    ElMessageBox.alert(
      `确定删除数据源<span style='color:#f00'>${names.join(',')}</span>?`,
      '删除数据源',
      {
        dangerouslyUseHTMLString:true,
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        draggable:true
      }
    ).then(()=>{
      emits('onDelete','multiple',ids.join(','))
    })
  }
</script>

<template>
  <div class="operation">
    <div>
      <el-button
        class="buttons"
        @click='openAdd'
        type="primary">
        新增
      </el-button>
      <el-button
        :disabled="tableSelections.length === 0"
        class="buttons"
        @click='batchDeleteSource'
        type="danger">
        删除
      </el-button>
    </div>
    <div class="search-input">
      <el-input
        v-model="queryParameters.datasourceName"
        placeholder="请输入数据源名称"
        @keyup.enter.native="datasourceEnter">
        <template #append>
          <el-button
            slot="append"
            :icon="Search"
            @click="datasourceEnter"></el-button>
        </template>
      </el-input>
      <el-popover
        placement="bottom"
        v-model="visible"
        popper-class="sort-size"
        trigger="click">
        <template #reference>
          <div class="popover-text">
            <span style="margin-left: 10px; cursor: pointer; color: #3e8ff0; font-size: 16px">排序</span>
            <el-icon style="color: #3e8ff0">
              <ArrowDown />
            </el-icon>
          </div>
        </template>
        <div
          class="sort-size"
          style="border-bottom: 1px solid #fafafa">
          <div
            v-for="(item, index) in datasourceFields"
            :key="index"
            class="selection-box">
            <div class="selected-flag">
              <el-icon
                v-if="queryParameters.selectField === item.value"
                style="color: #3e8ff0; font-size: 18px; font-weight: 600">
                <Check />
              </el-icon>
            </div>
            <div
              class="selection-name"
              @click="selectBack(item.value, 'fields')">
              {{ item.name }}
            </div>
          </div>
        </div>
        <div class="sort-size">
          <div
            v-for="(item, index) in sortOptions"
            :key="index"
            class="selection-box">
            <div class="selected-flag">
              <el-icon
                v-if="queryParameters.sortMethod === item.value"
                style="color: #3e8ff0; font-size: 18px; font-weight: 600">
                <Check />
              </el-icon>
            </div>
            <div
              class="selection-name"
              @click="selectBack(item.value, 'sortMethod')">
              {{ item.name }}
            </div>
          </div>
        </div>
      </el-popover>
    </div>
  </div>
  <div class="data-source-list">
    <el-table
      :data="props.table"
      border
      @selection-change='selectionChange'
      class="border-table">
      <el-table-column
        type="selection"
        width="40"
        align="center"></el-table-column>
      <el-table-column
        prop="name"
        label="名称"
        :show-overflow-tooltip="true"
        align="center"></el-table-column>
      <el-table-column
        prop="type"
        label="类型"
        align="center"></el-table-column>
      <el-table-column
        prop="address"
        label="连接参数"
        :formatter="connectParamConver"
        :show-overflow-tooltip="true"
        align="center"></el-table-column>
      <el-table-column
        prop="remark"
        label="描述"
        :show-overflow-tooltip="true"
        align="center"></el-table-column>
      <el-table-column
        prop="status"
        label="连接状态"
        width="90"
        align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '已连接' : '断开' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="注册时间"
        width="168"
        :show-overflow-tooltip="true"
        align="center"></el-table-column>
      <el-table-column
        label="操作"
        width="250"
        align="center">
        <template #default='{row}'>
          <div class='operation-box'>
            <el-button
              text
              :icon="check"
              size="small"
              type="primary">
              查看
            </el-button>|
            <el-button
              text
              :icon="Edit"
              size="small"
              type="info">
              编辑
            </el-button>|
            <el-button
              text
              :icon="Delete"
              size="small"
              @click='deleteSource(row)'
              type="danger">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="props.total"
      :page-size='props.pageSize'
      :current-page='props.currentPage'
      @current-change='pageChange'
      style="margin-top: 10px; float: right" />
  </div>
</template>

<style lang="less" scoped>
  .operation {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .buttons {
      width: 80px;
    }

    .search-input {
      height: 40px;
      display: flex;
      align-items: center;

      :deep(.el-input) {
        width: 300px;
        height: 40px;

        .el-input__wrapper {
          height: 100%;
          border: 1px solid #388bef;
          border-top-left-radius: 7px;
          border-bottom-left-radius: 7px;
          box-shadow: none;
        }

        .el-input-group__append {
          background: #388bef;
          border: 1px solid #388bef;
          border-top-right-radius: 7px;
          border-bottom-right-radius: 7px;
          box-shadow: none;

          button {
            color: #fff;
          }
        }
      }

      .popover-text {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  .data-source-list {
    width: 100%;
    height: calc(100% - 40px);
    padding-top: 10px;
    box-sizing: border-box;
    font-family: 'Microsoft YaHei';
    .border-table {
      :deep(th) {
        background: #fafafa !important;
      }
      :deep(.el-button) {
        margin:0px !important;
        span {
          margin-left: 1px;
        }
      }
      .operation-box{
        width:100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
      }
    }
  }
</style>
<style lang="less">
  .sort-size {
    width: 120px;
    display: flex;
    justify-content: space-around;
    flex-direction: column;
    font-size: calc(12px * var(--reScale));
    .selection-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .selection-name {
        width: calc(100% - 30px);
        box-sizing: border-box;
        padding: 5px 10px;
        cursor: pointer;
      }

      .selected-flag {
        width: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  //.border-table {
  //  th {
  //    background: #fafafa !important;
  //  }
  //}
</style>
